package com.juku2024.juku.tools;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import com.tbruyelle.rxpermissions2.RxPermissions;

public class PermissionTools {

    public static void checkPermission(FragmentActivity activity, OnPermissionCallback callback) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            new RxPermissions(activity)
                    .request(Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(aBoolean -> {
                        if (callback != null){
                            callback.onPermission(aBoolean);
                        }
                    }).isDisposed();
        } else {
            if (callback != null){
                callback.onPermission(true);
            }
        }
    }

    /**
     * 是如果应用之前请求过此权限但用户拒绝了请求，此方法将返回 true。如果用户在过去拒绝了权限请求，并在权限请求系统对话框中选择了 Don't ask again 选项，此方法将返回 false。如果设备规范禁止应用具有该权限，此方法也会返回 false。
     */
    public static boolean isShowPermissionUI(Activity activity, String[] permissions) {
        boolean isAllAllow = false;
        for (String permission : permissions) {
            boolean isRefuse = ActivityCompat.shouldShowRequestPermissionRationale(activity, permission);
            if (isRefuse) {
                isAllAllow = true;
                break;
            }
        }
        return isAllAllow;
    }

    public interface OnPermissionCallback{
        void onPermission(boolean isGranted);
    }
    /**
     * 判断权限集合
     */
    public static boolean hasAllPermissions(Context mContexts, String[] permissions) {
        for (String permission : permissions) {
            if (lacksPermission(mContexts,permission)) {
                return false;
            }
        }
        return true;
    }


    /**
     * 判断是否缺少权限
     */
    private static boolean lacksPermission(Context mContexts, String permission) {
        return ContextCompat.checkSelfPermission(mContexts, permission) ==
                PackageManager.PERMISSION_DENIED;
    }

}
